package com.softa.service.system.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageInfo;
import com.softa.annotation.ServiceLog;
import com.softa.bean.DataGridModel;
import com.softa.dao.dto.SysUserDTO;
import com.softa.dao.mapper.base.SysFileMapper;
import com.softa.dao.mapper.base.SysUserMapper;
import com.softa.dao.mapper.relation.system.SysFileRelationMapper;
import com.softa.dao.mapper.relation.system.SysUserRelationMapper;
import com.softa.dao.model.SysFile;
import com.softa.dao.model.SysResource;
import com.softa.dao.model.SysUser;
import com.softa.enummodel.FileTypeEnum;
import com.softa.service.encrypt.PasswordHelper;
import com.softa.service.system.UserService;
import com.softa.utils.Constants;
import com.softa.vo.DataGridRequest;
import com.softa.vo.QueryRequest;
import com.softa.dao.model.SysRole;
import com.softa.service.system.RoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 
* @ClassName: UserServiceImpl
* @Description: TODO
* @author yangl
*
 */
@SuppressWarnings("all")
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRelationMapper sysUserRelationMapper;
    
    @Resource
    private PasswordHelper passwordHelper;
    @Resource
    private RoleService roleService;

    @Autowired
    private SysFileMapper sysFileMapper;
    @Autowired
    private SysFileRelationMapper sysFileRelationMapper;
    
    /**
     * 创建用户
     * @param user
     */
    @ServiceLog(value="创建用户")
    public String createUser(SysUser user) {
    	DataGridModel dataGrid = new DataGridModel();
    	dataGrid.getParams().put("username", user.getUsername());
        boolean isName=this.isExists(dataGrid);
    	String str="录入成功";
    	if(isName){
    		str="1";//存在名称
    	}else{
			 //加密密码
			passwordHelper.encryptPassword(user);
			sysUserMapper.insertSelective(user);
    	}
        return str;
    }

    @ServiceLog(value="更新用户")
    public String updateUser(SysUserDTO sysUserDTO) {
	  DataGridModel dataGrid = new DataGridModel();
	  dataGrid.getParams().put("id", sysUserDTO.getId());
	  dataGrid.getParams().put("username", sysUserDTO.getUsername());
	  boolean isName = this.isExists(dataGrid);
	  String str = "修改成功";
	  if (isName) {
		str = "1";//存在名称
	  } else {
		SysUser user = new SysUser();
		BeanUtils.copyProperties(sysUserDTO, user);
		sysUserMapper.updateByPrimaryKeySelective(user);
		if (null != sysUserDTO.getPicId()) {
		    savePic(sysUserDTO.getPicId(), user.getId());
		}
	  }
	  return str;
    }

    @ServiceLog(value="删除用户")
    public void deleteUser(Long userId) {
    	SysUser sysUser = new SysUser();
		sysUser.setId(userId);
		sysUser.setIsshow(1);
    	sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    public boolean isExists(DataGridModel dataGrid){
    	List<SysUser> list=sysUserRelationMapper.selectByParam(dataGrid);
    	boolean flag=false;
    	if(list.size() > 0){
    		flag=true;
    	}
    	return flag;
    }
    
    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    @ServiceLog(value="修改密码")
    public void changePassword(Long userId, String newPassword) {
    	SysUser user =sysUserMapper.selectByPrimaryKey(userId);
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        sysUserMapper.updateByPrimaryKey(user);
    }

    @ServiceLog(value="查询单个用户对象")
    public SysUser findOne(Long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    @ServiceLog(value="查询所有用户信息")
    public List<SysUser> findAll() {
        return sysUserRelationMapper.selectByParam(new DataGridModel());
    }

	/**
	 * 根据用户名查找用户
	 */
	@Override
	public SysUser findAdminUser() {
		DataGridModel dataGrid = new DataGridModel();
		dataGrid.getParams().put("username", Constants.ADMIN);
		List<SysUser> list = sysUserRelationMapper.selectAdmin(dataGrid);
		if(list != null && list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}


    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    public SysUser findByUsername(String username) {
    	DataGridModel dataGrid = new DataGridModel();
    	dataGrid.getParams().put("username", username);
    	List<SysUser> list = sysUserRelationMapper.selectByParam(dataGrid);
    	if(list != null && list.size()>0){
    		return list.get(0);
    	}else{
    		return null;
    	}
    }

    /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    public Set<String> findRoles(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findRoles(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }

    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    public Set<String> findPermissions(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findPermissions(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }
    
    /**
     * 根据用户名查找其菜单
     * @param username
     * @return
     */
    public List<SysResource> findResourceList(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_LIST;
        }
        return roleService.findResourceList(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }
    
    public List<String> getListRoleIds(String str){
   	 List<String> list=new ArrayList<String>();
   	 if(StringUtils.isEmpty(str)){
   		 return list;
   	 }
   	  String[] roleIdStrs = str.split(",");
	      for(String roleIdStr : roleIdStrs) {
	          if(StringUtils.isEmpty(roleIdStr)) {
	              continue;
	          }
	          list.add(roleIdStr);
	      }
	      return list;
   }


	public PageInfo<SysUserDTO> queryUserByParam(DataGridRequest request, final QueryRequest queryRequest) {
		PageInfo<SysUserDTO> page = request.startPagePlugin().doSelectPageInfo(new ISelect() {
			@Override
			public void doSelect() {
				sysUserRelationMapper.selectByCondition(queryRequest);
			}
		});
		List<SysUserDTO> userList = page.getList();
		for(SysUserDTO user : userList){
			user.setRoleName(this.getRoleName(user.getRoleIds()));
		}
		return  page;
	}


	@Override
	public Long queryUserTotalByParam(DataGridModel dataGrid) {
		return sysUserRelationMapper.selectCountByCondition(dataGrid);
	}

	public String getRoleName(String code){
		SysRole o=roleService.findOne(code);
		String str=null;
		if(o != null){
			str=o.getName();
		}
		return str;
	}

	/**
	 * 判断用户名是否存在
	 * @param user
	 */
	@Override
	public Integer checkusername(SysUser user) {
		DataGridModel dataGrid = new DataGridModel();
		dataGrid.getParams().put("username", user.getUsername());
		boolean isName=this.isExists(dataGrid);
		Integer status = 0;
		if(isName){
			status=1;//存在名称
		}
		return status;
	}

    public void savePic(Long fileId, Long userId){
	  //先删除原来的
	  QueryRequest queryRequest = new QueryRequest();
	  queryRequest.getParams().put("pkeyId", userId.toString());
	  queryRequest.getParams().put("tableName", SysUser.class.getSimpleName());
	  queryRequest.getParams().put("fileType", FileTypeEnum.IMAGE.toString());
	  sysFileRelationMapper.deleteByPkeyIdAndTableName(queryRequest);
	  //保存新的
	  SysFile sysFile = new SysFile();
	  sysFile.setId(fileId);
	  sysFile.setPkeyId(userId.toString());
	  sysFile.setTableName(SysUser.class.getSimpleName());
	  sysFileMapper.updateByPrimaryKeySelective(sysFile);
    }
}
